<template>
  <div class="shopcar">
    <van-nav-bar
      title="购物车"
      left-text="返回"
      @click-left="back"
      :right-text="isExit ? '完成' : '编辑'"
      left-arrow
      @click-right="taggleExit"
    />

    <div class="car-banner">
      <img class="img-auto" src="../assets/images/shopbag_bg.png" alt="">
    </div>

    <!-- 购物车为空显示 -->
    <van-empty v-if="shopCarData.length <= 0" description="已经没有商品了">
      <van-button round type="default" class="bottom-button" @click="shopping"
        >逛一逛</van-button
      >
    </van-empty>

    <div
      v-else
      class="car-box"
      v-for="(item, i) in shopCarData"
      :key="item.sid"
    >
      <van-swipe-cell :disabled="!isExit">
        <div class="car-item">
          <div class="check">
            <van-checkbox
              v-model="item.isCheck"
              icon-size="20px"
              @change="oneSelect"
            ></van-checkbox>
          </div>
          <div class="pro-card">
            <div class="pro-img">
              <img class="img-auto" :src="item.small_img" alt="" />
            </div>
            <div class="pro-text">
              <div class="text-box">
                <div class="pro-names">
                  <div class="pro-name">{{ item.name }}</div>
                  <div class="pro-rule">{{ item.rule }}</div>
                </div>
                <div class="emname">{{ item.enname }}</div>
                <div class="count-box">
                  <div class="pro-price">&yen; {{ item.price }}</div>
                  <div class="pro-count">
                    <van-stepper
                      v-model="item.count"
                      theme="round"
                      button-size="20"
                      disable-input
                      @change="upDateShopCount(item.sid, item.count)"
                    />
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <template #right>
          <van-button
            square
            type="danger"
            text="删除"
            @click="removeShop([item.sid], i)"
          />
        </template>
      </van-swipe-cell>
    </div>

    <van-submit-bar
      v-show="!isExit"
      :price="total"
      button-text="提交订单"
      button-color="#307dd5"
      @submit="commit"
    >
      <van-checkbox v-model="checked" @click="allSelect">全选</van-checkbox>
    </van-submit-bar>

    <van-submit-bar
      v-show="isExit"
      button-text="删除"
      button-color="#307dd5"
      @submit="removeSelect"
    >
      <van-checkbox v-model="checked" @click="allSelect">全选</van-checkbox>
    </van-submit-bar>
  </div>
</template>

<script>
import "../assets/less/shopcar.less";
import { mapState, mapMutations } from "vuex";
export default {
  name: "ShopCar",
  data() {
    return {
      audio: "",
      isExit: false,
      checked: false,
      shopCarData: [],
      total: 0
    };
  },
  created() {
    this.getShopCarData();
  },
  computed: {
    ...mapState(["shopCarCount"]),
  },
  methods: {
    ...mapMutations(['changeShopCarCount']),

    taggleExit() {
      this.isExit = !this.isExit;
    },
    back() {
      this.$router.back();
    },
    shopping() {
      this.$router.push({ path: "/" });
    },

    // 获取购物车数据
    getShopCarData() {
      let tokenString = this.$cookies.get("tokenString");

      if (!tokenString) {
        console.log("浏览器token不存在");
        return;
      }

      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
      });

      this.axios({
        method: "GET",
        url: this.baseURL + "/findAllShopcart",
        params: {
          appkey: this.appkey,
          tokenString,
        },
      })
        .then((response) => {
          this.$toast.clear();
          // console.log(response);

          if (response.data.code === 700) {
            this.$toast({
              message: response.date.msg,
              forbidClick: true,
              duration: 1000,
            });
            this.$router.push({ name: "Login" });
          }

          if (response.data.code === 5000) {
            response.data.result.forEach((element) => {
              element.isCheck = false;
            });
            this.shopCarData = response.data.result;
          }
        })
        .catch((err) => {
          this.$toast.clear();
          console.error(err);
        });
    },

    // 修改购物车商品数量
    upDateShopCount(sid, count) {
      this.addTotal();
      let tokenString = this.$cookies.get("tokenString");

      if (!tokenString) {
        console.log("浏览器token不存在");
        return;
      }

      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
      });

      this.axios({
        method: "POST",
        url: this.baseURL + "/modifyShopcartCount",
        data: {
          appkey: this.appkey,
          tokenString,
          sid,
          count,
        },
      })
        .then((response) => {
          this.$toast.clear();
          // console.log(response);

          if (response.data.code === 700) {
            this.$toast({
              message: response.date.msg,
              forbidClick: true,
              duration: 1000,
            });
            this.$router.push({ name: "Login" });
          }

          if (response.data.code !== 6000) {
            this.$toast({
              message: response.date.msg,
              forbidClick: true,
              duration: 1000,
            });
          }
        })
        .catch((err) => {
          this.$toast.clear();
          console.error(err);
        });
    },

    // 全选
    allSelect() {
      this.shopCarData.forEach((item) => {
        item.isCheck = this.checked;
      });
      this.addTotal();
    },

    // 单选
    oneSelect() {
      this.addTotal();
      for (let i = 0; i < this.shopCarData.length; i++) {
        if (!this.shopCarData[i].isCheck) {
          this.checked = false;
          return;
        }
        this.checked = true;
      }
    },

    // 删除购物车
    removeShop(sid, index) {
      let tokenString = this.$cookies.get("tokenString");

      if (!tokenString) {
        console.log("浏览器token不存在");
        return;
      }

      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
      });

      this.axios({
        method: "POST",
        url: this.baseURL + "/removeShopcart",
        data: {
          appkey: this.appkey,
          tokenString,
          sids: JSON.stringify(sid),
        },
      })
        .then((response) => {
          this.$toast.clear();
          // console.log(response);

          if (response.data.code === 700) {
            this.$toast({
              message: response.date.msg,
              forbidClick: true,
              duration: 1000,
            });
            this.$router.push({ name: "Login" });
          }

          if (response.data.code == 7000) {
            if (index != undefined) {
              this.shopCarData.splice(index, 1);
              this.changeShopCarCount(this.shopCarCount - 1);
            } else {
              for (let i = 0; i < this.shopCarData.length; i++) {
                if (this.shopCarData[i].isCheck) {
                  this.shopCarData.splice(i, 1);
                  i--;
                } 
              }
              this.changeShopCarCount(this.shopCarData - sid.length);
              this.addTotal();
            }
          }
        })
        .catch((err) => {
          this.$toast.clear();
          console.error(err);
        });
    },

    // 删除选中商品
    removeSelect() {
      let sids = [];
      this.shopCarData.forEach((item) => {
        if (item.isCheck) {
          sids.push(item.sid);
        }
      });
      if (sids.length === 0) {
        this.$toast({
          message: "未选中商品",
          forbidClick: true,
          duration: 1000,
        });
        return;
      };
      this.removeShop(sids);
    },

    // 计算总价格
    addTotal() {
      let total = 0;
      this.shopCarData.forEach(item => {
        if (item.isCheck) {
          total += item.price * item.count;
        }
      })
      this.total = total * 100;
    },

    // 提交订单
    commit() {
      let sids = [];
      this.shopCarData.forEach((item) => {
        if (item.isCheck) {
          sids.push(item.sid);
        }
      });
      if (sids.length === 0) {
        this.$toast({
          message: "未选中商品",
          forbidClick: true,
          duration: 1000,
        });
        return;
      };
      this.$router.push({name: 'Pay', query: {sids: sids.join('-')}})
    }
  },
};
</script>
